package orz.mikeneck.server.locrec.controller;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletResponse;

import orz.mikeneck.server.locrec.exception.LocRecUserNotFoundException;
import orz.mikeneck.server.locrec.model.LocRecUserModel;
import orz.mikeneck.server.locrec.model.LocRecUserModelImpl;
import orz.mikeneck.server.locrec.persistent.LocRecUser;
import orz.mikeneck.server.locrec.persistent.utils.PersistenceManagerUtil;
import orz.mikeneck.server.locrec.utils.UserServiceUtil;

import com.google.appengine.api.users.UserService;

public class LocRecControllerImpl implements LocRecController<LocRecUser> {

	UserServiceUtil util;

	public LocRecControllerImpl(UserService service){
		this.util =
			new UserServiceUtil(service);
	}

	@Override
	public LocRecUser execute(HttpServletResponse resp){
		String email = util.getEmail();
		PersistenceManager manager = PersistenceManagerUtil.getManager();
		
		LocRecUserModel model = new LocRecUserModelImpl();
		try {
			return model
				.emailIs(email)
				.persistenceManagerIs(manager)
				.createSearchQuery()
				.getLocRecUser();
		} catch (LocRecUserNotFoundException e) {
			try {
				resp.sendRedirect("/location/signup.jsp");
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
			return null;
		} finally {
			manager.close();
		}
	}
}
